<template>
  <div class="son-container">
    <hr>
    <h2>Son组件 子组件 {{ pocketMoney }}</h2>
    <button @click="buyToys">儿子花钱买玩具了~</button>
    <hr>
    <GrandSon></GrandSon>
    <hr>
    <div>
      <span style="margin-right: 20px">count: {{ modelValue }}</span>
      <button @click="add">+1</button>
    </div>

  </div>
</template>


<script>

import GrandSon from "./GrandSon.vue";
import {inject} from "vue";
import {getRandomInt} from "../util/tool";
import emitter from "../util/mitt";

export default {
  name: "Son",
  props: {
    modelValue: {
      type: Number,
      default: 0
    }
  },
  components: {
    GrandSon
  },
  setup(props, {emit}) {
    // 接收祖先组件提供的数据
    const pocketMoney = inject('money');
    const changeMoney = inject('changeMoney');

    const buyToys = () => {
      // 买玩具所花的钱
      const money = getRandomInt(50, 150);
      console.log(`儿子买了一个玩具, 花了${money}元`)
      // 子组件消费了, 通知父组件APP.vue组件, 进行修改
      changeMoney(money)
    }

    // 监听事件中心的事件
    emitter.on('getMoney', (obj) => {
      console.log(obj, 'from emitter')
    })


    // add
    const add = () => {
      emit("update:modelValue", props.modelValue + 1)
    }

    return {
      pocketMoney,
      buyToys,
      add
    }
  }
}
</script>

<style scoped>

</style>
